import React from 'react';
import { Button, Text, View } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as AuthSession from 'expo-auth-session';

WebBrowser.maybeCompleteAuthSession();

const WECHAT_APPID = 'wx10684715b8f3b501';
const WECHAT_REDIRECT_URI = 'exp://10.1.129.54:8081';
const WECHAT_AUTH_URL = 'https://open.weixin.qq.com/connect/qrconnect';

const generateState = () => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let state = '';
    for (let i = 0; i < 16; i++) {
        state += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return state;
};

const WechatLogin = () => {
    const [request, response, promptAsync] = AuthSession.useAuthRequest({
        authUrl: `${WECHAT_AUTH_URL}?appid=${WECHAT_APPID}&redirect_uri=${encodeURIComponent(WECHAT_REDIRECT_URI)}&response_type=code&scope=snsapi_login&state=${generateState()}`,
    });

    React.useEffect(() => {
        if (response?.type === 'success') {
            const { code } = response.params;
            // 在这里使用 code 去换取 access_token
            console.log('Code:', code);
        }
    }, [response]);

    return (
        <View>
            <Button
                disabled={!request}
                title="使用微信登录"
                onPress={() => promptAsync()}
            />
        </View>
    );
};

export default WechatLogin;